//
//  YRJCountryDetailViewController.m
//  YanRenjie
//
//  Created by dllo on 15/10/24.
//  Copyright (c) 2015年 yanrenjie. All rights reserved.
//

#import "YRJCountryDetailViewController.h"
#import "YRJTripHeader.h"

@interface YRJCountryDetailViewController()<UITableViewDataSource, UITableViewDelegate, YRJGoFreedomTableViewCellDelegate>
@property(nonatomic, retain)UIScrollView *scrollView;
@property(nonatomic, retain)UITableView *tableView;
@property(nonatomic, retain)MBProgressHUD *hud;
@property(nonatomic, retain)NSMutableArray *hotCityArr;
@property(nonatomic, retain)NSMutableArray *hotMGuideArr;
@property(nonatomic, retain)NSArray *newDiscountArr;
@property(nonatomic, retain)NSArray *photosArr;
@property(nonatomic, retain)UIView *subview;
@property(nonatomic, retain)UILabel *entryContLabel;  // 说名
@property(nonatomic, retain)NSDictionary *countryInfoDic;
@end


@implementation YRJCountryDetailViewController
- (void)dealloc {
    [_string release];
    [_countryName release];
    [_hotCountrymodel release];
    [_countryModel release];
    [_scrollView release];
    [_tableView release];
    [_hud release];
    [_hotCityArr release];
    [_hotMGuideArr release];
    [_newDiscountArr release];
    [_photosArr release];
    [_subview release];
    
    [super dealloc];
}


#pragma mark - 轮播图滚动方法
- (void)changePicture {
    [self.scrollView setContentOffset:CGPointMake(self.scrollView.contentOffset.x + WIDTH, 0) animated:YES];
    // 判断是否到当前的最后一张, 如果到了, 需要把偏移量设置到第一张图片的位置
    if (self.scrollView.contentOffset.x == self.photosArr.count * WIDTH) {
        self.scrollView.contentOffset = CGPointMake(0, 0);
    }
}


- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    self.automaticallyAdjustsScrollViewInsets = YES;
    self.navigationController.navigationBar.translucent = NO;
    self.title = self.countryName;
    
    // 利用工具类实现的收藏, 如果用户登录了则运行收藏, 否则给出提示信息
    if ([YRJSaveTool isCountryInPlist:self.hotCountrymodel]) {
        self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"收藏" style:UIBarButtonItemStylePlain target:self action:@selector(click:)];
    } else {
        self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"已收藏" style:UIBarButtonItemStylePlain target:self action:@selector(click:)];
    }

    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT) style:UITableViewStyleGrouped];
    [self.view addSubview:self.tableView];
    self.tableView.backgroundColor = [UIColor whiteColor];
    [_tableView release];
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    self.countryInfoDic = [NSDictionary dictionary];
    
    self.subview = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SWIDTH, (300.0 / 667) * SHEIGHT)];
    self.tableView.tableHeaderView = self.subview;
    [_subview release];
   
    self.scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, SWIDTH, (200.0 / 667) * SHEIGHT)];
    [self.subview addSubview:self.scrollView];
    [_scrollView release];
    self.scrollView.pagingEnabled = YES;
    
    self.entryContLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, (200.0 / 667) * SHEIGHT, SWIDTH, 10000)];
    [self.subview addSubview:self.entryContLabel];
    [_entryContLabel release];
    self.entryContLabel.numberOfLines = 0;
    self.entryContLabel.textAlignment = NSTextAlignmentLeft;
    
    // 占位图
    self.hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    self.hud.labelText = @"Loading...";
    [self createData];
}


#if 0
#pragma mark -  普通方法, 收藏, 请求数据
- (void)saveAction:(UIButton *)button {
    NSString *sandBoxPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    NSString *docPath = [sandBoxPath stringByAppendingPathComponent:@"hot.plist"];
    NSLog(@"%@", docPath);
    // 直接归档会覆盖掉之前的数据, 所以先进行反归档, 然后添加进之后再进行归档操作
    NSMutableArray *countryArr = [NSKeyedUnarchiver unarchiveObjectWithFile:docPath];
    if (countryArr == nil) {
        countryArr = [NSMutableArray array];
    }
    [countryArr addObject:self.hotCountrymodel];
    [NSKeyedArchiver archiveRootObject:countryArr toFile:docPath];
    NSLog(@"%@", docPath);
}
#endif


#pragma mark - 利用工具类实现的收藏方法
- (void)click:(UIBarButtonItem *)button {
//    if ([YRJSingleton shareSingleton].isLogin) {
        NSLog(@"%@", button.title);
        if ([button.title isEqualToString:@"已收藏"]) {
            // 有一个提示窗口, 显示已收藏, 不需要重新收藏
            [YRJSaveTool cancelCountryInPlist:self.hotCountrymodel];
            button.title = @"收藏";
        } else {
            [YRJSaveTool saveCountryToPlist:self.hotCountrymodel];
            button.title = @"已收藏";
        }
//    } else {
//        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"请先登录" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
//        [alert show];
//    }
}


- (void)createData {
    NSString *strURL = [NSString  stringWithFormat:@"%@%@", @"http://open.qyer.com/qyer/footprint/country_detail?client_id=qyer_android&client_secret=9fcaae8aefc4f9ac4915&v=1&track_deviceid=867739013144832&track_app_version=6.8.1&track_app_channel=hiapk&track_device_info=bbk77_cu_ics2&track_os=Android4.0.4&app_installtime=1445390305001&lat=38.883466&lon=121.544431&country_id=", self.string];
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    [manager GET:strURL parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSDictionary *dic = responseObject;
        self.countryInfoDic = dic[@"data"];
        self.photosArr = dic[@"data"][@"photos"];
        NSLog(@"%@", self.photosArr);
        self.hotCityArr = [YRJHotCityModel baseModelByArr:dic[@"data"][@"hot_city"]];
        self.hotMGuideArr = [YRJHotCountryModel baseModelByArr:dic[@"data"][@"hot_mguide"]];
        self.newDiscountArr = [YRJNew_discountModel baseModelByArr:dic[@"data"][@"new_discount"]];
        
        self.scrollView.contentSize = CGSizeMake(SWIDTH * (self.photosArr.count + 1), 0);
        for (NSInteger i = 0; i < self.photosArr.count; i++) {
            UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(SWIDTH * i, 0, SWIDTH, (200.0 / 667) * SHEIGHT)];
            [imageView sd_setImageWithURL:[NSURL URLWithString:self.photosArr[i]] placeholderImage:[UIImage imageNamed:@"placeHold.png"]];
            [self.scrollView addSubview:imageView];
            [imageView release];
        }
        
        UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(SWIDTH * self.photosArr.count, 0, SWIDTH, (200.0 / 667) * SHEIGHT)];
        [imageView sd_setImageWithURL:[NSURL URLWithString:self.photosArr[0]] placeholderImage:[UIImage imageNamed:@"placeHold.png"]];
        [self.scrollView addSubview:imageView];
        [imageView release];
        
        self.entryContLabel.text = self.countryInfoDic[@"entryCont"];
        self.entryContLabel.font = [UIFont systemFontOfSize:14 * (WIDTH / 375)];
        self.entryContLabel.numberOfLines = 0;
        [self.entryContLabel sizeToFit];
        
        self.subview.frame = CGRectMake(0, 0, SWIDTH, self.scrollView.frame.size.height + self.entryContLabel.frame.size.height);
        
        [NSTimer scheduledTimerWithTimeInterval:5 target:self selector:@selector(changePicture) userInfo:nil repeats:YES];
        self.hud.hidden = YES;
        [self.tableView reloadData];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
    }];
}


#pragma mark - tableView 两个必须实现的协议方法
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 0) {
        return self.hotCityArr.count;
    } else {
        return 1;
    }
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    // 国家中的热门城市
    if (indexPath.section == 0) {
        static NSString *hotcity = @"hotcity";
        YRJHotCityTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:hotcity];
        if (!cell) {
            cell = [[[YRJHotCityTableViewCell  alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nil] autorelease];
        }
        if (self.hotCityArr.count != 0) {
            [cell.photoImageView sd_setImageWithURL:[NSURL URLWithString:[self.hotCityArr[indexPath.row] photo]] placeholderImage:[UIImage imageNamed:@"placeHold.png"]];
            cell.cnnameLabel.text = [self.hotCityArr[indexPath.row] cnname];
            cell.ennameLabel.text = [self.hotCityArr[indexPath.row] enname];

        }
        return cell;
    } else {
        // 旅游所值
        static NSString *goFreedomReuse = @"goFreedomReuse";
        YRJGoFreedomTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:goFreedomReuse];
        if (!cell) {
            cell = [[[YRJGoFreedomTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:goFreedomReuse] autorelease];
        }
        cell.delegate = self;
        // 将tableView 中cell的 collectionView要显示内容传到创建tableViewCell的地方, 在创建cell的地方对collectionView中的元素进行赋值
        cell.goFreedomArr = self.newDiscountArr;
        return cell;
    }
}


#pragma mark - tableView 的非必须实现的协议方法
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 2;
}


// 返回分区的行高
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        return (170.0 / 667) * SHEIGHT;
    } else {
        if (self.hotCityArr.count % 2 == 0) {
            return (260.0 / 667) * SHEIGHT * (self.hotCityArr.count / 2 + 1);
        } else {
            return (260.0 / 667) * SHEIGHT * (self.hotCityArr.count / 2 + 2);
        }
    }
}


// 给分区返回一个View头部
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UIView *headView = [[[UIView alloc] initWithFrame:CGRectMake((5.0 / 375) * WIDTH, 0, (365.0 / 375) * WIDTH, (60.0 / 667) * HEIGHT)] autorelease];
    headView.backgroundColor = [UIColor whiteColor];
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake((20.0 / 375) * WIDTH, (15.0 / 667) * HEIGHT, (100.0 / 375) * WIDTH, (30.0 / 667) * HEIGHT)];
    [headView addSubview:titleLabel];
    if (section == 0) {
        titleLabel.text = @"热门城市";
    } else {
        titleLabel.text = @"旅有所值";
    }
    [titleLabel release];
    UIButton *forMoreButton = [UIButton buttonWithType:UIButtonTypeSystem];
    forMoreButton.frame = CGRectMake((265.0 / 375) * WIDTH, (5.0 / 667) * HEIGHT, (100.0 / 375) * WIDTH, (30.0 / 667) * HEIGHT);
    [forMoreButton setTitle:@"查看全部 〉" forState:UIControlStateNormal];
    [forMoreButton setTintColor:[UIColor greenColor]];
    if (section == 0) {
        [forMoreButton addTarget:self action:@selector(forAllHotCityAction:) forControlEvents:UIControlEventTouchUpInside];
    } else {
        [forMoreButton addTarget:self action:@selector(forTripValuedAction:) forControlEvents:UIControlEventTouchUpInside];
    }
    
    [headView addSubview:forMoreButton];
    return headView;
}


#pragma mark - 实现热门城市分区查看全部热门城市按钮的方法, 以及旅有所值的查看全部的方法
// all hot city
- (void)forAllHotCityAction:(UIButton *)button {
    YRJAllHotCityViewController *allHotCityVC = [[YRJAllHotCityViewController alloc] init];
    [self.navigationController pushViewController:allHotCityVC animated:YES];
//    NSLog(@"111----->%@", self.string);
    allHotCityVC.string = self.string;
//    NSLog(@"222----->%@", allHotCityVC.string);
    [allHotCityVC release];
}


// it is value to triping
- (void)forTripValuedAction:(UIButton *)button {
    YRJAllTripValuedViewController *tripValuedVC = [[YRJAllTripValuedViewController alloc] init];
    [self.navigationController pushViewController:tripValuedVC animated:YES];
//    NSLog(@"333----->%@", self.string);
    tripValuedVC.string = self.string;
//    NSLog(@"444----->%@", tripValuedVC.string);
    [tripValuedVC release];
}


- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return (60.0 / 667) * HEIGHT;
}


#pragma mark - tableView cell 点击方法的实现
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        YRJCityDetailViewController *cityDetailVC = [[YRJCityDetailViewController alloc] init];
        [self.navigationController pushViewController:cityDetailVC animated:YES];
        [cityDetailVC release];
        cityDetailVC.string = (NSString *)[self.hotCityArr[indexPath.row] id];
        NSLog(@"%@", [self.hotCityArr[indexPath.row] id]);
        
    } else {
        YRJTripValuedWebViewController *tripValuedWebVC = [[YRJTripValuedWebViewController alloc] init];
        tripValuedWebVC.id = (NSString *)[self.newDiscountArr[indexPath.row] id];
        [self.navigationController pushViewController:tripValuedWebVC animated:YES];
        [tripValuedWebVC release];
    }
}


#pragma mark - 自定义协议的方法实现
- (void)pushToTripValuedViewController:(NSNumber *)id {
    YRJGoFreedomAndLocalTouristWebViewController *goFreedomAndLocalTouristWebVC = [[YRJGoFreedomAndLocalTouristWebViewController alloc] init];
    [self.navigationController pushViewController:goFreedomAndLocalTouristWebVC animated:YES];
    [goFreedomAndLocalTouristWebVC release];
    goFreedomAndLocalTouristWebVC.idNumber = id;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}
@end
